import React, { useEffect, useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Menu, Button, Popconfirm, Image, FormInstance } from 'antd';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  getClassMenuList,
  getShopGoods,
  addModifyClass,
  deleteClassGoods,
  updateClassGoods
} from '@/services/shop/api';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import OptForm from './OptForm';
import EditClassForm from './EditClassForm';
import { isExits, MsgType, replaceImgHost, showMsg } from '@/utils/utils';
import './style.less';
import BreadcrumbDept from '@/components/BreadcrumbDept';

const CategoryList: React.FC = () => {
  const [selectedMenuKey, setSelectedMenuKey] = useState<string>('');
  const [openMenuKey, setOpenMenuKey] = useState<string[]>([]);
  const [selectedMeun, setSelectedMenu] = useState<any>({});

  const [visible, setVisible] = useState(false);
  const [imgVisible, setImgVisible] = useState<boolean>(false);
  const [editClassFormVisible, setEditClassFormVisible] = useState<boolean>(false);
  const [menuList, setMenuList] = useState<any[]>([]);
  const [cacheAllMenuList, setCacheAllMenuList] = useState<any[]>([]);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();

  const [selectedRows, setSelectedRows] = useState<SHOPAPI.ShopGoods[]>([]);
  const [params, setParams] = useState<any>({});

  const columns: ProColumns<SHOPAPI.ShopGoods>[] = [
    {
      title: '一级分类',
      dataIndex: 'class_id',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        options: cacheAllMenuList.map(item => {
          return {
            label: item.class_name,
            value: item.class_id
          }
        })
      }
    },
    {
      title: '分类名称',
      dataIndex: 'class_name',
      hideInTable: true,
      fieldProps: {
        placeholder: '输入分类名称',
        onPressEnter: (e: any) => {
          searchBtnClick();
          e.preventDefault();
        }
      }
    },
    {
      title: '图片',
      align: 'center',
      width: 130,
      search: false,
      render: (dom, entity) => {
        return <div style={{ display: 'flex', justifyContent: 'center' }}>
          <Image
            preview={false}
            height={60}
            src={replaceImgHost(entity.attach_list[0].attach_thumb_url || '')}
          />
          </div>
      }
    },
    {
      title: '品牌',
      dataIndex: 'brand_name',
      search: false
    },
    {
      title: '名称',
      dataIndex: 'shop_goods_name',
      width: 200,
      search: false
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id',
      search: false
    },
    {
      title: '添加时间',
      search: false,
      width: '16%',
      render: (dom, entity) => {
        return entity.create_date + ' ' + entity.create_time
      }
    }
  ];

  // 获取左侧菜单
  const fetchClassMenuList = async (first?: boolean) => {
    try {
      const data = (await getClassMenuList()) || [];
      setMenuList(data);
      setCacheAllMenuList(data);
      if (data.length > 0 && first) {
        setParams({
          pre_class_id: data[0].class_id
        });
        setSelectedMenuKey(data[0].class_id);
        setSelectedMenu({ ...data[0] });
      }
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  /**
   * 添加，修改分类
   * @param data
   * @returns
   */
  const handleAddClass = async (data: any) => {
    try {
      await addModifyClass(data);
      showMsg('已保存', MsgType.SUCCESS);
      fetchClassMenuList();
      return true;
    } catch (error) {
      showMsg(error?.data?.errmsg);
      return false;
    }
  }

  const handleAddGoods = async (data: any) => {
    try {
      await updateClassGoods(data);
      showMsg('已保存', MsgType.SUCCESS);
      return true;
    } catch (error) {
      showMsg(error?.data?.errmsg);
      return false;
    }
  }

  useEffect(() => {
    fetchClassMenuList(true);
  }, []);

  const updateClassName = (item: any, cName: string) => {
    const search = <span className='search'>{cName}</span>;
    return item.class_name.split(cName).reduce((total: any, curr: any, currIdx: number, arr: any) => {
      return <>{total}{search}{curr}</>;
    });
  };

  const deepClone = (obj: any) => {
    return JSON.parse(JSON.stringify(obj));
  };

  const searchBtnClick = () => {
    const fValues = formRef.current?.getFieldsValue();
    const cName = fValues.class_name, cId = fValues.class_id;
    let $menuList, $selectedMenuKey = '', $openMenuKey, $params;
    if (cName) {
      if (cId) {
        const selMenu = deepClone(cacheAllMenuList.find(item => item.class_id === cId));
        const searchMenu = selMenu['sec_class_list']?.filter((item: any) => item?.class_name?.includes(cName));
        if (searchMenu.length > 0) {
          searchMenu.forEach((item: any) => {
            item.class_name = updateClassName(item, cName);
          });
          const class_id = searchMenu[0].class_id;
          $menuList = [{ ...selMenu, sec_class_list: searchMenu }];
          $selectedMenuKey = class_id;
          $openMenuKey = [cId];
          $params = { shop_class_id: class_id };
        } else {
          $params = { pre_class_id: 'null' }; // 查一个不存在的值
        }
      } else {
        let firstMatchKey: any, isPre;
        const menuList = cacheAllMenuList.map(item => {
          let menu;
          if (item.class_name?.includes(cName)) {
            menu = { ...item };
            if (!firstMatchKey) {
              firstMatchKey = menu.class_id;
              isPre = true;
            }
          }
          const subMenu = deepClone(item?.sec_class_list?.filter((subItem: any) => subItem.class_name?.includes(cName)));
          if (subMenu.length > 0) {
            if (!menu) {
              menu = { ...item };
            }
            menu.sec_class_list = subMenu;
            if (!firstMatchKey) {
              firstMatchKey = subMenu[0].class_id;
              isPre = false;
            }
          }
          return menu;
        }).filter(item => item);
        $menuList = deepClone(menuList);
        $menuList.forEach((item: any) => {
          if (item.class_name.includes(cName)) {
            item.class_name = updateClassName(item, cName);
          }
          item.sec_class_list = item.sec_class_list?.map((subItem: any) => {
            subItem.class_name = updateClassName(subItem, cName);
            return subItem;
          });
        });
        $selectedMenuKey = firstMatchKey;
        $openMenuKey = menuList.map(item => item.class_id);
        if (firstMatchKey) {
          $params = isPre ? { pre_class_id: firstMatchKey } : { shop_class_id: firstMatchKey };
        } else {
          $params = { pre_class_id: 'null' };
        }
      }
    } else {
      const class_id = cId ? cId : cacheAllMenuList[0]?.class_id;
      $menuList = cacheAllMenuList;
      $selectedMenuKey = class_id;
      $openMenuKey = [class_id];
      $params = { pre_class_id: class_id };
    }
    setMenuList($menuList || []);
    setSelectedMenuKey($selectedMenuKey || '');
    setOpenMenuKey($openMenuKey || []);
    if ($selectedMenuKey && (params.pre_class_id === $selectedMenuKey || params.shop_class_id === $selectedMenuKey) && params.current === 1) {
      actionRef.current?.reload();
    } else {
      setParams({ ...$params, current: 1 });
    }
  };

  return (
    <PageContainer extra={[
      <BreadcrumbDept />
    ]} breadcrumb={{}}>
      <ProTable<SHOPAPI.ShopGoods, COMMON.PageParams>
        rowKey="sort"
        headerTitle="分类下商品列表"
        className='category-index-table'
        actionRef={actionRef}
        formRef={formRef}
        params={params}
        manualRequest={true}
        style={{ height: window.innerHeight - 110 }}
        rowSelection={{
          onChange: (selectedKeys, selectRows) => {
            setSelectedRows(selectRows);
          }
        }}
        request={async (params: any) => {
          try {
            actionRef?.current?.clearSelected!();
            const data: SHOPAPI.ShopGoodsList = await getShopGoods({ ...params, class_flag: '0' });
            return {
              data: data.record_list,
              success: true,
              total: data.sum_record_num
            };
          } catch (error) {
            showMsg(error?.data?.errmsg);
            return {
              data: [],
              success: true,
              total: 0
            };
          }
        }}
        pagination={{
          showQuickJumper: true
        }}
        bordered
        search={{
          span: 6,
          optionRender: (searchConfig, formProps, dom) => [
            <Button type='primary' onClick={searchBtnClick}>查询</Button>
          ]
        }}
        columns={columns}
        options={false}
        toolBarRender={
          () => [
            isExits('600603002') &&
            <Button
              key="edit"
              disabled={!selectedMenuKey}
              onClick={() => {
                setVisible(true);
              }}
              icon={<EditOutlined />}
              type="primary">
              编辑此分类下商品
            </Button>,
            isExits('600603003') &&
            <Popconfirm
              key="delete"
              okText="确认删除"
              cancelText="再想想"
              placement="topRight"
              onConfirm={async () => {
                try {
                  let pre_class_id = params.pre_class_id;
                  if (!pre_class_id) {
                    const tmpId = params.shop_class_id;
                    pre_class_id = cacheAllMenuList.find(item => !!item.sec_class_list.find((i: any) => i.class_id === tmpId))?.class_id;
                  }
                  const delParams = { shop_goods_ids: selectedRows.map(item => item.shop_goods_id), pre_class_id };
                  if (selectedMenuKey !== pre_class_id) {
                    delParams['class_id'] = selectedMenuKey;
                  }
                  await deleteClassGoods(delParams);
                  showMsg('已保存', MsgType.SUCCESS);
                  actionRef.current?.clearSelected?.();
                  actionRef.current?.reload();
                } catch (error) {
                  showMsg(error?.data?.errmsg);
                }
              }}
              title="您即将删除分类下选中的商品，是否继续？">
              <Button
                disabled={selectedRows.length == 0}
                icon={<DeleteOutlined />}
                type="primary">删除分类下选定商品</Button>
            </Popconfirm>
          ]
        }
        tableRender={(_, dom) => (
          <div className="menu-wrap">
            <div className="table-side">
              <div className="menu-top">
                <span>分类树</span>
                {
                  isExits('600603001') &&
                  <span className="edit" onClick={() => {
                    setEditClassFormVisible(true);
                  }}><EditOutlined style={{ marginRight: 5 }} />编辑分类</span>
                }
              </div>
              <Menu
                selectedKeys={[selectedMenuKey]}
                // openKeys={[...openMenuKey]}
                className="side-menu"
                selectable={true}
                onSelect={e => {
                  let selectedPreClassId = e.key, openMenuKey = e.key, p = { ...params } as any, selectedMenu;
                  if (e.keyPath.length > 1) { // 二级
                    selectedPreClassId = e.keyPath[1];
                    openMenuKey = e.keyPath[1];
                    p.shop_class_id = e.key;
                    delete p['pre_class_id'];
                    for (let i = 0, len = menuList.length; i < len; i++) {
                      selectedMenu = menuList[i].sec_class_list?.filter((item: any) => item.class_id === e.key)[0];
                      if (selectedMenu)
                        break;
                    }
                  } else { // 一级
                    p.pre_class_id = e.key;
                    delete p['shop_class_id'];
                    selectedMenu = menuList.find(m => m.class_id === e.key)
                  }
                  setSelectedMenuKey(e.key);
                  setOpenMenuKey([openMenuKey]);
                  setParams(p);
                  const pName = cacheAllMenuList.find(item => item.class_id === selectedPreClassId)?.class_name;
                  setSelectedMenu({ ...selectedMenu, pName: pName });
                }}
                mode="inline">
                {
                  menuList.filter(item => !!item).map(item => {
                    return <React.Fragment key={item.class_id}>
                      {
                        item.sec_class_list?.length ?
                          <Menu.SubMenu key={item.class_id} title={item.class_name} onTitleClick={e => {
                            // 子菜单标题点击必然是一级菜单
                            setSelectedMenuKey(e.key);
                            setOpenMenuKey([e.key]);
                            const p = {
                              ...params,
                              pre_class_id: e.key,
                              current: 1
                            };
                            delete p['shop_class_id'];
                            setParams(p);
                            const menu = menuList.find(m => m.class_id === e.key)
                            setSelectedMenu({ ...menu });
                          }}>
                            {
                              item.sec_class_list.map((sec: any) => {
                                return <Menu.Item key={sec.class_id}>{sec.class_name}</Menu.Item>
                              })
                            }
                          </Menu.SubMenu>
                          :
                          <Menu.Item key={item.class_id}>{item.class_name}</Menu.Item>
                      }
                    </React.Fragment>
                  })
                }
              </Menu>
            </div>

            <div className="center">
              {dom}
            </div>
          </div>
        )}
      />

      {
        visible && <OptForm
          currentRow={selectedMeun}
          handleModalVisible={setVisible}
          handleAdd={handleAddGoods}
          actionRef={actionRef} />
      }

      {
        editClassFormVisible && <EditClassForm
          handleAdd={handleAddClass}
          handleModalVisible={setEditClassFormVisible} />
      }
    </PageContainer>
  );
};
export default CategoryList;
